<template>
  <div class="build-config-container">
    <div class="form-and-result">
      <div class="form-panel">
        <HostMessage :form="form" :configs-data="configsData" @templateChange="onTemplateChange" />
        <AdBuildForm :use-dynamic-inputs="true" :form="form" :config-result="configResult" :is-example="isExample" />
        <FormActions
          :is-example="isExample"
          :config-result="configResult"
          :host="form.host"
          :dirpath="form.dirpath"
          :template-name="form.templateName"
          @generateExample="toggleExample"
          @generateConfig="handleInputChange"
          @copyConfig="copyConfig"
        />
      </div>

      <AdConfigResult :config-result="configResult" />

    </div>
  </div>

</template>

<script>
import HostMessage from './components/HostMessage.vue'
import AdBuildForm from './components/AdBuildForm.vue'
import AdConfigResult from './components/AdConfigResult.vue'
import FormActions from './components/FormActions.vue'
import { configsData } from '@/assets/data/configsdata'
import { buildConfig, fillINPUT, getExampleForm } from '@/assets/data/configBuilder'

export default {
  name: 'AutoAd',
  components: {
    HostMessage,
    AdBuildForm,
    AdConfigResult,
    FormActions
  },
  data() {
    return {
      adtype: 'gptslotdiv',
      isExample: false,
      originalForm: null,
      form: {
        host: '',
        dirpath: '',
        templateName: Object.keys(configsData)[0],
        html: {}
      },
      configsData,
      configResult: ''
    }
  },
  watch: {
    'form.templateName': {
      immediate: true,
      handler(newVal) {
        if (!newVal) return
        this.isExample = false
        const template = this.configsData[newVal]
        if (template && template.html) {
          this.form.html = JSON.parse(JSON.stringify(template.html))
          this.form.host = template.host || ''
          this.form.dirpath = ''
          this.configResult = ''
          this.$set(this.form.html, 'interstitial', '')
          this.$set(this.form.html, 'anchor', '')
        }
      }
    },
    'form.host': 'handleInputChange',
    'form.dirpath': 'handleInputChange',
    'form.html': {
      deep: true,
      handler() {
        this.handleInputChange()
      }
    }
  },
  methods: {
    toggleExample() {
      if (this.isExample) {
        // 取消示例，恢复之前数据
        if (this.originalForm) {
          this.form = JSON.parse(JSON.stringify(this.originalForm))
        } else {
          // 如果没有备份，清空
          this.form.host = ''
          this.form.dirpath = ''
          this.form.html = {}
          this.configResult = ''
        }
        this.isExample = false
      } else {
        // 备份当前数据
        this.originalForm = JSON.parse(JSON.stringify(this.form))

        // 加载示例
        const example = getExampleForm(this.adtype)
        if (!example) {
          this.$message.error(`未找到 ${this.adtype} 的示例数据`)
          return
        }

        this.form.host = example.host || 'www.aa.com'
        this.form.dirpath = example.dirpath || 'path'

        Object.keys(this.form.html).forEach(key => {
          if (example.html && example.html.hasOwnProperty(key)) {
            this.$set(this.form.html, key, example.html[key])
          }
        })
        this.isExample = true

        this.$nextTick(() => {
          this.handleInputChange()
        })
      }
    },
    handleInputChange() {
      if (this.form.host.trim() !== '') {
        this.configResult = buildConfig(this.form)
        this.configResult = fillINPUT(this.configResult, this.form.html, this.adtype)
      } else {
        this.configResult = ''
      }
    },
    copyConfig() {
      navigator.clipboard.writeText(this.configResult).then(() => {
        this.$message.success('复制成功！')
      }).catch(() => {
        this.$message.error('复制失败，请手动复制')
      })
    },
    onTemplateChange() {
      // this.form.host = '';
      // this.form.dirpath = '';
      // this.configResult = '';
    }
  }
}
</script>

<style scoped>
.build-config-container {
  padding: 20px;
}

.form-and-result {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-panel {
  flex: 1;
}

/* 横屏时使用左右布局 */
@media (min-width: 768px) {
  .form-and-result {
    flex-direction: row;
  }
}
</style>
